from django.shortcuts import render_to_response
from django.template import RequestContext
from muser.models import User, UserProfile, Book, BookProfile, Reserving
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.views.generic import list_detail
from django.shortcuts import get_object_or_404
from django.http import HttpResponse

def book_index(request):
	'''
	Book index and list
	'''
	try:
		kword = request.GET['w']
		mbooks = Book.objects.filter(title__icontains=kword)
	except KeyError:
		mbooks = Book.objects.all()

	pag = Paginator(mbooks, 13)

	try:
		p = int(request.GET.get('p', '1'))
	except ValueError:
		p = 1

	try:
		books = pag.page(p)
	except (EmptyPage, InvalidPage):
		books = pag.page(pag.num_pages)

	template = 'mbook/book_index.html'
	context = {
		'books': books,
	}

	return render_to_response(template, context, RequestContext(request))

def book_detail(request, book_id):
	'''
	Book basic info. and profile
	'''
	book = get_object_or_404(Book, pk=book_id)
	book_profile = book.bookprofile

	r = int(request.GET.get('r', '-1'))
	if r == 1:
		book_profile.num_reserving += 1
		book_profile.save()
		Reserving.objects.get_or_create(user_reserving=request.user.userprofile, book_reserved=book_profile)
	 
	return list_detail.object_detail(
		request,
		queryset = Book.objects.all(),
		template_name = 'mbook/book_detail.html',
		template_object_name = 'book',
		extra_context = { 'book_profile': book_profile },
		object_id = book_id,
	)
